package com.book.ordermanagement.listener;

import com.book.ordermanagement.command.OrderCommand;
import com.book.ordermanagement.invoke.OrderCommandInvoke;
import com.book.ordermanagement.state.OrderState;
import com.book.ordermanagement.state.OrderStateChangeAction;
import com.book.pojo.Order;
import com.book.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 监听类，用于监听订单消息和传递消息给spring状态机
 * @date 2023/12/20 20:26
 */
@Component
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListener {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private OrderCommandInvoke invoke;
    @Autowired
    private OrderCommand orderCommand;

    @OnTransition(source = "ORDER_WAIT_PAY", target = "ORDER_WAIT_SEND")
    public boolean payToSend(Message<OrderStateChangeAction> message) {
        // 从状态机里边获取订单信息
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(String.valueOf(OrderState.ORDER_WAIT_PAY))) {
            throw new RuntimeException("Order state is error !!");
        }
        // 修改状态存入redis里边
        order.setOrderState(String.valueOf(OrderState.ORDER_WAIT_SEND));
        redisUtils.set(order.getOrderId(), order, 900);
        // 命令模式  命令具体执行者去执行订单操作
        invoke.invoke(orderCommand, order);
        return true;

    }

    @OnTransition(source = "ORDER_WAIT_SEND", target = "ORDER_WAIT_RECEIVE")
    public boolean sendToReceive(Message<OrderStateChangeAction> message) {
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(String.valueOf(OrderState.ORDER_WAIT_SEND))) {
            throw new RuntimeException("Order state is error !!");
        }
        order.setOrderState(String.valueOf(OrderState.ORDER_WAIT_RECEIVE));
        redisUtils.set(order.getOrderId(), order, 900);
        // 命令模式
        invoke.invoke(orderCommand, order);
        return true;
    }

    @OnTransition(source = "ORDER_WAIT_RECEIVE", target = "ORDER_FINISH")
    public boolean receiveTo(Message<OrderStateChangeAction> message) {
        Order order = (Order) message.getHeaders().get("order");
        if (!order.getOrderState().equals(String.valueOf(OrderState.ORDER_WAIT_RECEIVE))) {
            throw new RuntimeException("Order state is error !!");
        }
        // 说明订单完成,直接从redis删除
        redisUtils.remove(order.getOrderId());
        // 命令模式
        invoke.invoke(orderCommand, order);
        return true;

    }


}
